package upload

import (
	"os"
	"path"
	"strings"

	"gitee.com/cyanbleeze/go-image-management/global"
	"gitee.com/cyanbleeze/go-image-management/pkg/util"
)

func GetFileName(name string) string {
	name = path.Base(name)
	ext := GetFileExt(name)
	fileName := strings.TrimSuffix(name, ext)
	fileName = util.EncodeMD5(fileName)

	return fileName + ext
}
func CreateSavePath(dst string, perm os.FileMode) error {
	err := os.MkdirAll(dst, perm)
	if err != nil {
		return err
	}

	return nil
}

func GetFileExt(name string) string {
	return path.Ext(name)
}

func GetSavePath() string {
	return global.AppSetting.UploadSavePath
}

func CheckSavePath(dst string) bool {
	_, err := os.Stat(dst)
	return os.IsNotExist(err)
}

func CheckMaxSize(size int64) bool {
	maxSize := int64(global.AppSetting.UploadImageMaxSize) << 20
	return size <= maxSize
}

func CheckContainExt(name string) bool {
	ext := strings.ToUpper(GetFileExt(name))
	for _, allowExt := range global.AppSetting.UploadImageAllowExts {
		if strings.ToUpper(allowExt) == ext {
			return true
		}
	}
	return false
}

func CheckPermission(dst string) bool {
	_, err := os.Stat(dst)
	return os.IsPermission(err)
}
